<template>
  <div class="AddEquipment">
    <div class="cus-title">
      <h4>新增RFID设备</h4>
    </div>
    <div class="cus-update">
      <el-form ref="form" :model="BindForm" :rules="rules" label-width="120px" label-position="left">
        <el-form-item label="商品:" prop="goods">
          <el-col :span="24">
            <el-input v-model="BindForm.goods" clearable :disabled="true" :style="'width: 100%; max-width: ' + maxWidth" />
          </el-col>
        </el-form-item>
        <el-form-item label="门店:" prop="storeId">
          <el-col :span="24">
            <el-select v-model="BindForm.storeId" :disabled="true" clearable filterable placeholder="请选择门店" :style="'width: 100%; max-width: ' + maxWidth">
              <el-option v-for="(item, index) in list" :key="index" :value="item.id" :label="item.storeName" />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="设备编号:" prop="equipmentCode">
          <el-col :span="24">
            <el-input
              v-model="BindForm.equipmentCode"
              type="textarea"
              :autosize="{ minRows: 7 }"
              resize="none"
              placeholder="添加多个请用英文“逗号”隔开"
              style="width: 400px;"
            />
          </el-col>
        </el-form-item>
        <!--        <el-form-item label="收费模板:" prop="chargeTemplateId">-->
        <!--          <el-col :span="24">-->
        <!--            <SelectCollectMoneyTemplate v-model="BindForm.chargeTemplateId" />-->
        <!--          </el-col>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="submit">确认新增</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { Loading } from 'element-ui'
import { addRFID } from '@/api/lockItem'
import { commodityList } from '@/api/commodity'
import { storeList } from '@/api/shop'
/** 新增RFID设备 */
export default {
  name: 'AddEquipment',
  data() {
    var validateEquCode = (rule, value, callback) => {
      var Regx = /^[0-9,]*$/
      if (value && value.length > 0 && !Regx.test(value)) {
        callback(new Error('请输入正确的设备编号'))
      } else {
        callback()
      }
    }
    return {
      maxWidth: '400px',
      goodsInfo: null,
      BindForm: {
        goods: null,
        commodityId: null,
        storeId: null,
        equipmentCode: null
      },
      BindTable: [],
      formData: null,
      list: [],
      submitForm: {
        skuInfo: [],
        skuName: '',
        commodityId: null,
        storeId: null,
        equipmentCode: null
      },
      rules: {
        goods: [{ required: true, message: '请选择商品', trigger: 'blur' }],
        storeId: [{ required: true, message: '请选择门店', trigger: 'change' }],
        equipmentCode: [{ required: true, message: '请输入设备编号', trigger: 'change' }, { validator: validateEquCode, trigger: 'change' }]
        // chargeTemplateId: [{ required: true, message: '请选择收费规则', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      const params = this.$dd(this.$route.query.p)
      this.goodsInfo = params.goodsInfo
      this.BindForm.storeId = params.storeId.toString()
      this.loadTableData()
      this.getStoreList()

      console.log(this.goodsInfo)
      this.submitForm.commodityId = this.goodsInfo.goodsId
      this.submitForm.storeId = params.storeId
      this.submitForm.skuName = this.goodsInfo.goodsSpec.replace(',', ';')
      this.BindForm.goods = this.goodsInfo.goodsName + '(' + this.submitForm.skuName + ')'
    },
    loadTableData() {
      const vm = this
      const data = {
        hasSku: 1,
        page: vm.page,
        limit: vm.limit
      }
      if (vm.goodsInfo.goodsName) {
        data['commodityName'] = vm.goodsInfo.goodsName
      }
      commodityList(data).then(res => {
        vm.BindTable = res.data.data.list ? res.data.data.list : []
        const tempGoods = this.$XEUtils.find(this.BindTable, item => item.goodsId === this.goodsInfo.goodsId)
        if (tempGoods.skuList && tempGoods.skuList.length > 0) {
          this.formData = {
            list: []
          }
          tempGoods.skuList.forEach((skuItem, index) => {
            skuItem.specList.forEach((specItem, nextIndex) => {
              this.formData.list.push({
                skuId: skuItem.skuId,
                skuName: skuItem.name,
                specId: specItem.id,
                specName: specItem.name
              })
            })
          })
        }
        const selectSkuList = this.goodsInfo.goodsSpec.split(',')
        const goodsSkuList = []
        selectSkuList.forEach((selectItem, selectIndex) => {
          const selectSku = {
            skuName: selectItem.split(':')[0],
            specName: selectItem.split(':')[1]
          }
          goodsSkuList.push(selectSku)
        })
        this.formData.list.forEach((item, formIndex) => {
          goodsSkuList.forEach((goodsSkuItem, goodsSkuIndex) => {
            if (item.skuName === goodsSkuItem.skuName && item.specName === goodsSkuItem.specName) {
              this.submitForm.skuInfo.push(item)
            }
          })
        })
      }).catch(res => {
        if (res && res.data && res.data.errno !== 0) {
          this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    },
    getStoreList() {
      const vm = this
      const data = {
        province: null,
        city: null,
        area: null,
        searchKey: null,
        page: 1,
        limit: 0
      }
      storeList(data).then(res => {
        vm.list = res.data.data.list
        console.log(vm.list)
      }).catch(res => {
        if (res && res.data && res.data.errno !== 0) {
          this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    },
    resetForm() {
      const vm = this
      vm.submitForm.equipmentCode = null
      vm.BindForm.equipmentCode = null
    },
    submit() {
      const vm = this
      vm.$refs.form.validate((valid) => {
        if (valid) {
          const loadingInstance = Loading.service({ fullscreen: true })
          /* const data = vm.$XEUtils.clone(vm.BindForm, true)*/
          /* data['commodityId'] = data.goods.goodsId
          data['storeId'] = parseInt(data['storeId'])

          if (data.goods.selectedSku) {
            data['skuInfo'] = data.goods.selectedSku
          }
          if (data.goods.goodsSkuNames) {
            data['skuName'] = data.goods.goodsSkuNames
          }
          delete data.goods*/
          this.submitForm.equipmentCode = this.BindForm.equipmentCode
          addRFID(this.submitForm).then(res => {
            loadingInstance.close()
            vm.$message.success('新增RFID设备成功')
            vm.$store.dispatch('tagsView/delView', vm.$route)
            vm.$router.go(-1)
          }).catch(res => {
            loadingInstance.close()
            if (res && res.data && res.data.errno !== 0) {
              this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.AddEquipment {
  padding: 30px;
  .cus-update {
    padding: 20px 30px;
    padding-bottom: 0px;
    margin-bottom: 30px;
    border: 1px solid #eee;

    .cus-input {
      max-width: 400px;
    }
  }
}
</style>
